#include <iostream>
#include <string>
#include <pthread.h>
#include <vector>
#include <unistd.h>

using namespace std;

pthread_cond_t gcond = PTHREAD_COND_INITIALIZER;//条件变量
pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER;//互斥锁

void *MasterCore(void *args)
{
    sleep(3);
    cout<<"Master 开始工作..." << endl;
    string name = static_cast<char *>(args);
    while (true)
    {
        // 将线程唤醒
        //pthread_cond_signal(&gcond);
        pthread_cond_broadcast(&gcond);
        cout<<"唤醒一个线程" << endl;
        sleep(1);
    }
    return nullptr;
}

void *SlaverCore(void *args)
{
    string name = static_cast<char *>(args);
    while (true)
    {
        //加锁
        pthread_mutex_lock(&gmutex);
        //设置条件变量，让线程在等待队列
        pthread_cond_wait(&gcond, &gmutex);
        cout << "线程在等待... " << name << endl;
        //解锁
        pthread_mutex_unlock(&gmutex);
    }
    return nullptr;
}

void StartSlaver(vector<pthread_t> *tidptr, int num = 3)
{
    for (int i = 0; i < num; i++)
    {
        pthread_t tid;
        char* name = new char[64];
        snprintf(name, 64, "thread-%d", i+1);
        int n = pthread_create(&tid, nullptr, SlaverCore, name);
        if (n == 0)
        {
            cout << "create success..." << name << endl;
            tidptr->emplace_back(tid);
        }
    }
}

void StartMaster(vector<pthread_t> *tidptr)
{
    pthread_t tid;
    int n = pthread_create(&tid, nullptr, MasterCore, (void *)"Master thread");
    if (n == 0)
    {
        cout << "create Master success..." << endl;
    }
    tidptr->emplace_back(tid);
}
void Waitthreads(vector<pthread_t> &tidptr)
{
    for(auto thread:tidptr)
    {
        pthread_join(thread, nullptr);
    }
}
int main()
{
    vector<pthread_t> tids;
    StartMaster(&tids);
    StartSlaver(&tids, 5);
    Waitthreads(tids);
    return 0;
}